<template>
  <div class="tiger-slot-container">
    <div class="tiger-slot-card">
      <button class="close-button" @click="closeSlot">×</button>
      <h1 class="title">老虎机抽奖 🎰</h1>
      
      <div class="slot-content">
        <!-- 左侧结果展示区域 -->
        <div class="results-section">
          <h2>中奖名单</h2>
          <div class="winner-list">
            <div 
              v-for="(winner, index) in displayedWinners" 
              :key="index"
              class="winner-item"
              :class="{ placeholder: winner.isPlaceholder }"
            >
              <div class="winner-rank">{{ winner.rank }}</div>
              <div class="winner-name">{{ winner.name }}</div>
            </div>
          </div>
        </div>
        
        <!-- 右侧老虎机区域 -->
        <div class="slot-machine-section">
          <div class="slot-machine">
            <div class="reel-container">
              <!-- 只显示一个轮子 -->
              <div 
                class="reel"
                :class="{ 'spinning': isSpinning && !isReelStopped[0] }"
                :style="{ 
                  transform: `translateY(${reelPosition[0]}px)`,
                  transition: isReelStopped[0] ? 'transform 0.5s ease-out' : 'none'
                }"
              >
                <div 
                  v-for="(item, itemIndex) in reelItems" 
                  :key="itemIndex"
                  class="reel-item"
                >
                  {{ item }}
                </div>
              </div>
            </div>
            
            <div class="reel-mask"></div>
          </div>
          
          <!-- 控制区域 -->
          <div class="slot-controls">
            <div class="input-group">
              <label for="winnerCount">抽奖人数：</label>
              <input 
                type="number" 
                id="winnerCount"
                v-model.number="selectedCount" 
                min="1" 
                :max="participants.length"
                class="count-input"
                :disabled="isSpinning"
              />
            </div>
            
            <button 
              @click="startSlot" 
              class="spin-btn"
              :disabled="selectedCount <= 0 || selectedCount > participants.length"
            >
              {{ isSpinning ? '停止抽奖' : '开始抽奖' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TigerSlot',
  emits: ['close'],
  data() {
    return {
      participants: [
        '张三', '李四', '王五', '赵六', '钱七',
        '孙八', '周九', '吴十', '郑一', '王二',
        '冯三', '陈四', '褚五', '卫六', '蒋七',
        '沈八', '韩九', '杨十', '朱一', '秦二'
      ],
      selectedCount: 3,
      isSpinning: false,
      isReelStopped: [false], // 只需要一个轮子的状态
      reels: [[]], // 只需要一个轮子
      reelPosition: [0], // 只需要一个轮子的位置
      reelItems: [],
      winners: [],
      spinIntervals: [null], // 只需要一个定时器
      // 轮子速度控制参数
      spinSpeed: [1], // 初始速度
      maxSpinSpeed: 15, // 最大速度
      targetItems: [], // 停止时的目标项
      stopTimeouts: [null], // 停止轮子的延时器
      // 减速控制参数
      decelerationStartTime: 0, // 减速开始时间
      decelerationDuration: 3000, // 减速持续时间（3秒）
      // 中奖者显示间隔控制
      winnerDisplayTimeouts: [], // 中奖者显示的延时器
      // 控制按钮状态
      isDisplayingWinners: false // 是否正在显示中奖者
    }
  },
  computed: {
    displayedWinners() {
      const result = [];
      
      // 添加实际中奖者
      this.winners.forEach((winner, index) => {
        result.push({
          ...winner,
          rank: index + 1
        });
      });
      
      // 添加占位符
      const placeholdersNeeded = Math.max(0, this.selectedCount - this.winners.length);
      for (let i = 0; i < placeholdersNeeded; i++) {
        result.push({
          name: '等待开奖',
          rank: this.winners.length + i + 1,
          isPlaceholder: true
        });
      }
      
      return result;
    }
  },
  methods: {
    closeSlot() {
      this.$emit('close')
    },
    initializeReels() {
      // 创建轮子项，包含所有参与者姓名
      this.reelItems = [...this.participants]
      // 为了滚动效果，重复添加几次
      for (let i = 0; i < 3; i++) {
        this.reelItems = this.reelItems.concat(this.participants)
      }
      
      // 初始化轮子（只有一个轮子）
      this.reels = [[...this.reelItems]]
      this.reelPosition = [0]
      this.isReelStopped = [false]
      this.winners = [] // 清空中奖名单
      this.spinSpeed = [1] // 重置轮子速度
      this.isDisplayingWinners = false // 重置中奖者显示状态
      
      // 清理可能存在的延时器
      this.stopTimeouts.forEach(timeout => {
        if (timeout) clearTimeout(timeout)
      })
      this.stopTimeouts = [null]
      
      // 清理可能存在的中奖者显示延时器
      this.winnerDisplayTimeouts.forEach(timeout => {
        if (timeout) clearTimeout(timeout)
      })
      this.winnerDisplayTimeouts = []
    },
    startSlot() {
      // 确保选中人数在有效范围内
      if (this.selectedCount <= 0) {
        alert('抽奖人数必须大于0')
        return
      }
      
      if (this.selectedCount > this.participants.length) {
        alert(`抽奖人数不能超过参与人数(${this.participants.length}人)`)
        return
      }
      
      if (!this.isSpinning) {
        // 开始抽奖
        this.isSpinning = true
        this.isDisplayingWinners = false
        this.initializeReels()
        
        // 随机选择获奖者，数量等于输入框中的值
        const shuffled = [...this.participants].sort(() => 0.5 - Math.random())
        this.targetItems = shuffled.slice(0, this.selectedCount)
        
        // 启动轮子（只有一个轮子）
        this.startReel(0)
      } else {
        // 停止抽奖
        this.stopSlot()
      }
    },
    startReel(reelIndex) {
      if (reelIndex >= this.reels.length) return
      
      this.spinIntervals[reelIndex] = setInterval(() => {
        // 加速阶段：逐渐增加速度直到达到最大速度
        if (this.spinSpeed[reelIndex] < this.maxSpinSpeed) {
          this.spinSpeed[reelIndex] += 0.5
        }
        
        this.reelPosition[reelIndex] -= this.spinSpeed[reelIndex]
        // 当位置超出范围时重置，创建无限滚动效果
        if (Math.abs(this.reelPosition[reelIndex]) > this.reelItems.length * 30) {
          this.reelPosition[reelIndex] = 0
        }
      }, 30)
    },
    stopReel(reelIndex) {
      if (this.spinIntervals[reelIndex]) {
        // 清除原来的定时器
        clearInterval(this.spinIntervals[reelIndex])
        this.spinIntervals[reelIndex] = null
      }
      
      // 记录减速开始时间
      this.decelerationStartTime = Date.now()
      
      // 设置减速定时器
      this.spinIntervals[reelIndex] = setInterval(() => {
        // 计算已经过去的时间
        const elapsed = Date.now() - this.decelerationStartTime
        // 计算减速进度（0到1之间）
        const progress = Math.min(elapsed / this.decelerationDuration, 1)
        
        // 使用缓动函数实现更自然的减速效果
        // 这里使用easeOutCubic缓动函数：(x - 1)^3 + 1
        const easeProgress = 1 - Math.pow(1 - progress, 3)
        
        // 根据进度计算当前速度（从最大速度减到0）
        this.spinSpeed[reelIndex] = this.maxSpinSpeed * (1 - easeProgress)
        
        // 继续更新轮子位置
        this.reelPosition[reelIndex] -= this.spinSpeed[reelIndex]
        
        // 如果减速时间已到，完全停止
        if (progress >= 1) {
          // 完全停止
          this.spinSpeed[reelIndex] = 0
          clearInterval(this.spinIntervals[reelIndex])
          this.spinIntervals[reelIndex] = null
          
          // 依次添加中奖者到名单，每个间隔1秒
          this.addWinnersWithDelay()
          
          this.isReelStopped[reelIndex] = true
        }
      }, 30)
    },
    // 依次添加中奖者到名单，每个间隔1秒
    addWinnersWithDelay() {
      // 清空中奖者列表
      this.winners = []
      
      // 为每个中奖者设置延时显示
      this.targetItems.forEach((winnerName, index) => {
        const timeout = setTimeout(() => {
          this.winners.push({ name: winnerName })
          
          // 如果是最后一个中奖者，更新按钮状态
          if (index === this.targetItems.length - 1) {
            this.isDisplayingWinners = false
            this.isSpinning = false
          }
        }, index * 100) // 每个中奖者间隔1秒显示
        this.winnerDisplayTimeouts.push(timeout)
      })
      
      // 标记正在显示中奖者
      this.isDisplayingWinners = true
    },
    stopSlot() {
      // 停止轮子（只有一个轮子）
      if (!this.isReelStopped[0]) {
        this.stopReel(0)
      }
    }
  },
  mounted() {
    this.initializeReels()
  },
  beforeUnmount() {
    // 清理定时器
    this.spinIntervals.forEach(interval => {
      if (interval) clearInterval(interval)
    })
    
    // 清理延时器
    this.stopTimeouts.forEach(timeout => {
      if (timeout) clearTimeout(timeout)
    })
    
    // 清理中奖者显示延时器
    this.winnerDisplayTimeouts.forEach(timeout => {
      if (timeout) clearTimeout(timeout)
    })
  }
}
</script>

<style scoped>
.tiger-slot-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

:root {
  --vt-c-gold: #d4af37;
}

.tiger-slot-card {
  background: linear-gradient(135deg, rgba(44, 62, 80, 0.9), rgba(26, 26, 46, 0.9));
  border-radius: 20px;
  padding: 30px;
  width: 90%;
  max-width: 900px;
  height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
  border: 1px solid var(--vt-c-gold);
  backdrop-filter: blur(10px);
  position: relative;
  text-align: center;
}

.title {
  color: var(--vt-c-gold);
  margin-top: 0;
  text-align: center;
  text-shadow: 0 0 10px rgba(212, 175, 55, 0.5);
  font-size: 2rem;
  border-bottom: 2px solid rgba(212, 175, 55, 0.3);
  padding-bottom: 15px;
}

.close-button {
  position: absolute;
  top: 15px;
  right: 15px;
  background: rgba(212, 175, 55, 0.2);
  border: 1px solid var(--vt-c-gold);
  color: var(--vt-c-gold);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 1.2rem;
  transition: all 0.3s ease;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  background: rgba(212, 175, 55, 0.4);
  transform: rotate(90deg);
}

.slot-content {
  display: flex;
  flex: 1;
  gap: 30px;
  margin-top: 20px;
}

.results-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 15px;
  padding: 20px;
  border: 1px solid rgba(212, 175, 55, 0.3);
  text-align: left;
}

.results-section h2 {
  color: var(--vt-c-gold);
  text-align: center;
  margin-top: 0;
  text-shadow: 0 0 8px rgba(212, 175, 55, 0.5);
  border-bottom: 1px solid rgba(212, 175, 55, 0.3);
  padding-bottom: 10px;
}

.winner-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.winner-list::-webkit-scrollbar {
  width: 6px;
}

.winner-list::-webkit-scrollbar-thumb {
  background: rgba(212, 175, 55, 0.5);
  border-radius: 3px;
}

.winner-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin: 10px 0;
  border-radius: 10px;
  background: linear-gradient(135deg, rgba(212, 175, 55, 0.2), rgba(212, 175, 55, 0.1));
  border: 1px solid rgba(212, 175, 55, 0.3);
  transition: all 0.3s ease;
}

.winner-item.placeholder {
  opacity: 0.5;
  background: rgba(255, 255, 255, 0.05);
  border: 1px dashed rgba(255, 255, 255, 0.2);
}

.winner-item:not(.placeholder):hover {
  transform: translateX(5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.winner-rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffd166, #ffa502);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #1a1a1a;
  margin-right: 15px;
  flex-shrink: 0;
}

.winner-name {
  color: #fff;
  font-weight: bold;
  flex: 1;
  font-size: 1.1rem;
}

.winner-item.placeholder .winner-name {
  color: #aaa;
  font-style: italic;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 0.7;
  }
  100% {
    opacity: 0.5;
  }
}

.slot-machine-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 15px;
  padding: 20px;
  border: 1px solid rgba(212, 175, 55, 0.3);
}

.slot-machine {
  width: 200px;
  height: 150px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 15px;
  position: relative;
  overflow: hidden;
  border: 2px solid var(--vt-c-gold);
  box-shadow: 0 0 20px rgba(212, 175, 55, 0.3);
  margin-bottom: 30px;
}

.reel-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100%;
}

.reel {
  width: 33%;
  height: 100%;
  position: relative;
}

.reel-item {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 1.2rem;
  font-weight: bold;
  text-shadow: 0 0 8px rgba(212, 175, 55, 0.7);
}

.reel.spinning {
  transition: none;
}

.reel-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.5);
  pointer-events: none;
}

.reel-mask::before,
.reel-mask::after {
  content: '';
  position: absolute;
  left: 0;
  width: 100%;
  height: 40px;
}

.reel-mask::before {
  top: 0;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), transparent);
}

.reel-mask::after {
  bottom: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
}

.slot-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  gap: 20px;
}

.input-group {
  display: flex;
  align-items: center;
  color: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  font-size: 1.2rem;
  font-weight: bold;
}

.count-input {
  padding: 8px 15px;
  border-radius: 50px;
  border: 2px solid rgba(212, 175, 55, 0.7);
  background: rgba(255, 255, 255, 0.3);
  color: #fff;
  text-align: center;
  width: 80px;
  font-size: 1rem;
  margin-left: 10px;
}

.count-input:disabled {
  opacity: 0.6;
}

.count-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.count-input:focus {
  outline: none;
  border-color: var(--vt-c-gold);
  background: rgba(212, 175, 55, 0.2);
}

.spin-btn {
  background: linear-gradient(135deg, #ffd166, #ffa502);
  border: none;
  border-radius: 50px;
  color: #1a1a1a;
  padding: 15px 40px;
  cursor: pointer;
  font-weight: bold;
  font-size: 1.2rem;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
  width: 80%;
  max-width: 200px;
}

.spin-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #ffdc73, #ffae0f);
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}

.spin-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .slot-content {
    flex-direction: column;
  }
  
  .results-section {
    order: 2;
  }
  
  .slot-machine-section {
    order: 1;
  }
  
  .slot-controls {
    max-width: 100%;
  }
}
</style>